# coding：utf-8
import requests  # 先导入爬虫的库，不然调用不了爬虫的函数
import time
import datetime
import os
import io
import re
import sys
from lxml import etree
from pprint import pprint
import json
from openpyxl import load_workbook


class P_TP_H():
    # label_signal = pyqtSignal(str, str)

    def __init__(self, parent=None):
        pass
        # file = open("./log.txt", 'w').close()

    def echo(self, *args):
        print(datetime.datetime.now())
        pprint([str(i) for i in args])

    def request_source(self, url):
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            'Host': "jcfx.tjj.zj.gov.cn:6443",
            "Referer": "https://jcfx.tjj.zj.gov.cn:6443/autocode-project/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "Windows"
        }
        response = requests.get(url, headers=headers)
        return response

    def run_it(self, text):
        url = "https://jcfx.tjj.zj.gov.cn:6443/autocode-clusterapi-pub/api/stats/query/mobile/des/{}/3".format(text)
        response = P_TP_H.request_source(url)

        data = json.loads(response.text)
        result = []
        for r in data["data"]["Codes"]:
            result.append([r["Category"], r["Code"], r["Exact"], r["Weight"], r["Name"]])
        return result


if __name__ == "__main__":
    P_TP_H = P_TP_H()
    wb = load_workbook("./test_.xlsx")
    sh = wb["待查询名称"]
    nrow = sh.max_row
    row = 1
    page = 0
    for i in range(1, nrow):
        quote = sh.cell(i + 1, 1).value
        k = P_TP_H.run_it(quote)
        P_TP_H.echo(i, nrow + 1 - i)
        # print("result", k)
        wb["查询结果"].cell(row, 1).value = str(i)
        wb["查询结果"].cell(row, 2).value = quote
        for r in range(k.__len__()):

            wb["查询结果"].cell(row, 3).value = k[r][0]
            wb["查询结果"].cell(row, 4).value = k[r][4]
            wb["查询结果"].cell(row, 5).value = k[r][1]
            wb["查询结果"].cell(row, 6).value = k[r][3]

            row += 1
        time.sleep(0.1)
        if i % 30 == 0:
            P_TP_H.echo("--------------------------------------------------------保存结果-----------------------------------------------------------------")
            page += 1
            wb.save("./result/test_result{}.xlsx".format(page))
    # wb.save("./test_result.xlsx")
